package com.yfp.operation.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yfp.common.redis.service.RedisService;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.domain.MachineDO;
import com.yfp.operation.domain.PositionDO;
import com.yfp.operation.domain.PositionSharing;
import com.yfp.operation.mapper.MachineMapper;
import com.yfp.operation.service.*;
import com.yfp.system.api.domain.SysRole;
import com.yfp.operation.service.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 *
 * @description 针对表【machine(设备机器表)】的数据库操作Service实现
 * @createDate 2024-04-17 15:55:42
 */
@Service
@Slf4j
public class MachineServiceImpl extends ServiceImpl<MachineMapper, MachineDO> implements MachineService {

    @Resource
    private PositionService positionService;
    @Resource
    private PositionSharingService positionSharingService;
    @Resource
    private MachineMapper machineMapper;
    @Resource
    private WorkOrderService workOrderService;
    @Resource
    private RedisService redisService;
    @Resource
    private OrderDetailService orderDetailService;


    /**
     * 根据用户id查询设备列表
     *
     * @param userId 用户id
     * @return 设备列表
     */
    @Override
    public List<MachineDO> getMachineOperationByUserId(Long userId) {
        log.info("入参用户id:{}", userId);
        LambdaQueryWrapper<PositionDO> query = Wrappers.lambdaQuery(PositionDO.class);
        query.eq(PositionDO::getOperationUserId, userId);
        List<String> positionIds = positionService.list(query).stream().map(PositionDO::getPositionId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(positionIds)) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<MachineDO> machineQuery = Wrappers.lambdaQuery(MachineDO.class);
        machineQuery.in(MachineDO::getPositionId, positionIds);
        List<MachineDO> list = this.list(machineQuery);
        list.sort(Comparator.comparing(MachineDO::getMachineId));
        return list;
    }

    /**
     * 根据用户id查询投资人设备列表
     *
     * @param userId 用户id
     * @return 设备列表
     */
    @Override
    public List<MachineDO> getMachineInvestorByUserId(Long userId) {
        log.info("入参用户id:{}", userId);
        List<SysRole> rolesInfoList = SecurityUtils.getLoginUser().getRolesInfoList();
        // 创客管理员角色
        Boolean investorManager = false;
        for (SysRole sysRole : rolesInfoList) {
            if (sysRole.getRoleKey().equals("investorManager")) {
                investorManager = true;
                break;
            }
        }
        LambdaQueryWrapper<PositionDO> query = Wrappers.lambdaQuery(PositionDO.class);
        if (!investorManager) {
            query.eq(PositionDO::getInvestorUserId, userId);
        } else {
            userId = null;
        }
        List<String> positionIds1 = positionService.list(query).stream().map(PositionDO::getPositionId).collect(Collectors.toList());
        List<String> positionIds2 = positionSharingService.getByUserId(userId).stream().map(PositionSharing::getPositionId).collect(Collectors.toList());

        ArrayList<String> positionIds = new ArrayList<>();
        positionIds.addAll(positionIds1);
        positionIds.addAll(positionIds2);
        if (CollectionUtils.isEmpty(positionIds)) {
            return Collections.emptyList();
        }

        LambdaQueryWrapper<MachineDO> machineQuery = Wrappers.lambdaQuery(MachineDO.class);
        machineQuery.in(MachineDO::getPositionId, positionIds);
        List<MachineDO> list = this.list(machineQuery);
        list.sort(Comparator.comparing(MachineDO::getMachineId));
        return list;
    }

    /**
     * 根据用户id和设备id查询设备
     *
     * @param userId    用户id
     * @param machineId 设备id
     * @return 设备
     */
    @Override
    public MachineDO getMachineOperationByUserIdAndMachineId(Long userId, String machineId) {
        LambdaQueryWrapper<PositionDO> query = Wrappers.lambdaQuery(PositionDO.class);
        query.eq(PositionDO::getOperationUserId, userId);
        List<String> positionIds = positionService.list(query).stream().map(PositionDO::getPositionId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(positionIds)) {
            return null;
        }

        LambdaQueryWrapper<MachineDO> machineQuery = Wrappers.lambdaQuery(MachineDO.class);
        machineQuery.in(MachineDO::getPositionId, positionIds);
        machineQuery.eq(MachineDO::getMachineId, machineId);
        return this.getOne(machineQuery);
    }

    /**
     * 检测设备故障
     *
     * @return 设备列表
     */
    @Transactional
    @Override
    public List<MachineDO> detectDeviceFaults() {
        LambdaQueryWrapper<MachineDO> query = Wrappers.lambdaQuery(MachineDO.class);
        // "0"表示异常
        query.eq(MachineDO::getOutMealCheck, 0);
        return this.list(query);
    }

    @Override
    public Integer getMachineType(String machineId) {
        return machineMapper.getMachineType(machineId);
    }

    @Override
    public List<MachineDO> getDisconnection() {
        return machineMapper.getDisconnection();
    }

    @Override
    public MachineDO getMachine(String machineId) {
        return machineMapper.getMachine(machineId);
    }

    /**
     * 检测设备套餐制作是否异常
     */
    @Transactional
    @Override
    public void checkMachineMealAnomaly() {
//        redisService.deleteObject(CacheConstants.MACHINE_ORDER_DETAIL_STATUS_LIST);
//        List<RedisOrderDetail> cacheList = redisService.getCacheList(CacheConstants.MACHINE_ORDER_DETAIL_STATUS_LIST);
//        OrderDetailDO orderDetailDO = null;
//        long totalBetween = 0;
//        for (RedisOrderDetail redisOrderDetail : cacheList) {
//            // 输出相差的分钟数
//            long between = DateUtils.between(redisOrderDetail.getQueueTime());
//            orderDetailDO = orderDetailService.findById(redisOrderDetail.getDetailId());
//            totalBetween = orderDetailDO.getCount()*3;
//            // 判断排队时间是否大于count*3 ,并且 状态为等待制作、制作中的订单
//            log.info("OrderDetailId: {}, totalBetween: {}, between: {}, getStatus: {}", orderDetailDO.getOrderDetailId(), totalBetween, between, orderDetailDO.getStatus());
//            if (between >= totalBetween
//                    && ( orderDetailDO.getStatus().equals(PackageStatusEnums.WaitingToBeMade.getStatus())
//                    || orderDetailDO.getStatus().equals(PackageStatusEnums.InTheMaking.getStatus())
//                    || orderDetailDO.getStatus().equals(PackageStatusEnums.MakeExceptions.getStatus())
//                    )) {
//                log.info("检测设备套餐制作是否异常,OrderDetailId:{},totalBetween:{}", redisOrderDetail.getDetailId(), totalBetween);
//                // 更新数据库
//                LambdaUpdateWrapper<OrderDetailDO> update = Wrappers.lambdaUpdate(OrderDetailDO.class);
//                update.set(OrderDetailDO::getStatus, PackageStatusEnums.MakeExceptions.getStatus());
//                update.set(OrderDetailDO::getQueueTime, null);
//                update.set(OrderDetailDO::getUpdateTime, new Date());
//                update.eq(OrderDetailDO::getOrderDetailId, redisOrderDetail.getDetailId());
//                orderDetailService.update(update);
//
//                // 修改完异常订单后，删除redis中的对应数据
//                redisService.removeListItem(CacheConstants.MACHINE_ORDER_DETAIL_STATUS_LIST, redisOrderDetail);
//            } else if (orderDetailDO.getStatus().equals(PackageStatusEnums.APPLY_REFUND.getStatus())
//                    ||orderDetailDO.getStatus().equals(PackageStatusEnums.MadeDone.getStatus())
//                    ||orderDetailDO.getStatus().equals(PackageStatusEnums.PickupIsComplete.getStatus())
//                    ||orderDetailDO.getStatus().equals(PackageStatusEnums.Refunded.getStatus())){
//
//                // 更新数据库
//                LambdaUpdateWrapper<OrderDetailDO> update = Wrappers.lambdaUpdate(OrderDetailDO.class);
//                update.set(OrderDetailDO::getQueueTime, null);
//                update.set(OrderDetailDO::getUpdateTime, new Date());
//                update.eq(OrderDetailDO::getOrderDetailId, redisOrderDetail.getDetailId());
//                orderDetailService.update(update);
//
//                // 修改完异常订单后，删除redis中的对应数据
//                redisService.removeListItem(CacheConstants.MACHINE_ORDER_DETAIL_STATUS_LIST, redisOrderDetail);
//            }
//        }
    }

    @Override


    public List<String> machineNames(List<String> machineIds) {
        return machineMapper.machineNames(machineIds);
    }

    @Override
    public List<MachineDO> findAll() {
        return machineMapper.findAll();
    }

    @Override
    public List<MachineDO> listMachine(MachineDO machineDO) {
        return machineMapper.listMachine(machineDO);
    }

    @Override
    public List<MachineDO> listMachineByPositionIds(List<String> positionIds) {
        if (CollUtil.isEmpty(positionIds)) {
            return new ArrayList<>();
        }
        return machineMapper.listMachineByPositionIds(positionIds);
    }
}




